package com.lsp.microcommon.Interceptor;


import com.lsp.microcommon.annotation.NoLogin;
import com.lsp.microcommon.constants.CommonConstants;
import com.lsp.microcommon.exception.CommonException;
import com.lsp.microcommon.utils.JwtUtils;
import com.lsp.microcommon.utils.RedisUtils;
import com.lsp.microcommon.utils.UserUtils;
import io.jsonwebtoken.Claims;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

public class LoinInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//      handler指的是拦截的对象
//        控制层方法内部被封装为HandlerMethod对象
        if(!(handler instanceof HandlerMethod)){
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
//        判断方法是否使用了对应的注解
        if(method.isAnnotationPresent(NoLogin.class)){
            return true;
        }

        //        登陆成功后会将token值发送给前端
//        前端发送请求时，需要将token放在请求头中发送给后台
        String token = request.getHeader("Token");
        if (token == null || token.isEmpty()) {
            throw new CommonException(CommonConstants.NO_LOGIN, "请先登录");
        }
//        解析失败，说明jwt过期或者被篡改
        Claims claims = null;
        try {
            claims = JwtUtils.parseJWT(token);
            RedisUtils.setValue("uid", claims.get("uid"));
        } catch (Exception e) {
            throw new CommonException(CommonConstants.NO_LOGIN, "登录过期");
        }

        UserUtils.setUser((Integer) claims.get("uid"));
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserUtils.removeUser();
    }
}
